package com.kltn.zigo;

import org.json.JSONObject;

import com.android.zing.ZME_DialogListener;
import com.android.zing.ZME_Error;
import com.android.zing.dialog.ZME_DialogError;
import com.kltn.zigo.data.UserInfoData;
import com.kltn.zigo.data.insert.DetailGroupCustomerPlaceInsert;
import com.kltn.zigo.zingme.sdk.BaseRequestListener;
import com.kltn.zigo.zingme.sdk.ZingMeSDK;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener {

	public static final String TAG = "ZiGo";

    private SharedPreferences mPrefs;
    private SharedPreferences.Editor editor;
    
    private boolean flatLogin = true;
    
	private Button btnCheckIn;
	private Button btnNearHere;
	private Button btnNewPost;
	private Button btnTopList;
	
    private MenuItem btnLogin;
    private MenuItem btnLogout;
    private MenuItem btnSearch;
    private MenuItem btnProfile;
    
    String username = "";
	String displayname = "";
	String tinyurl = "";
	int uid = 0;  

    @Override
    public void onResume() {
    	super.onResume();
    	//if(flatLogin == false)
    	{
    		requestZingMeLogin();
    		flatLogin = true;
    		/*String fields = "id,username,displayname,tinyurl";
    		ZingMeSDK.getInstance().getMeInfo(MainActivity.this.getApplicationContext(), fields, new MeInfoRequestListener());
    		if(uid != 0)
    			new ConfirmUserInfo().execute();*/
    	}
    }
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ActionBar actionBar = getActionBar();		
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#b51d21")));
		
		mPrefs = getPreferences(MODE_PRIVATE); 
		
		//actionBar.hide();
		
		/*ActionBar actionBar = getActionBar();
	    // add the custom view to the action bar
	    actionBar.setCustomView(R.layout.mainscreen);
	    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
	        | ActionBar.DISPLAY_SHOW_HOME);*/
	    
		//Anh xa cac button tu giao dien qua code activity
		btnCheckIn = (Button) findViewById(R.id.btn_check_in);
		btnNearHere = (Button) findViewById(R.id.btn_near_here);
		btnNewPost = (Button) findViewById(R.id.btn_new_post);
		btnTopList = (Button) findViewById(R.id.btn_top_list);
		//edtSearch = (EditText) findViewById(R.id.edtSearch);
		
		if( ZingMeSDK.getInstance().isSessionValid(MainActivity.this)){
			btnCheckIn.setVisibility(View.VISIBLE);
		}		
		
		//Event click button Check in
		btnCheckIn.setOnClickListener(this);
		
		//Event click button Near here
		btnNearHere.setOnClickListener(this);
		
		//Event click button New post
		btnNewPost.setOnClickListener(this);
		
		//Event click button Top list
		btnTopList.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
			case R.id.btn_check_in:
			{				
				Intent i=new Intent(MainActivity.this,NearHereActivity.class);
				i.putExtra("userid",Integer.toString(uid));
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", displayname);
		        i.putExtra("useravatarurl", tinyurl);
			    startActivity(i);
			    break;
			}
			case R.id.btn_near_here:
			{
				Intent i=new Intent(MainActivity.this,ListUserActivity.class);
				i.putExtra("userid",Integer.toString(uid));
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", displayname);
		        i.putExtra("useravatarurl", tinyurl);
			    startActivity(i);
				break;
			}
			case R.id.btn_new_post:
			{
				Intent i=new Intent(MainActivity.this,NewPostActivity.class);
				i.putExtra("userid",Integer.toString(uid));
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", displayname);
		        i.putExtra("useravatarurl", tinyurl);
			    startActivity(i);
				break;
			}
			case R.id.btn_top_list:
			{
				Intent i=new Intent(getApplicationContext(),ListPlaceActivity.class);
		        i.putExtra("userid",Integer.toString(uid));
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", displayname);
		        i.putExtra("useravatarurl", tinyurl);
			    startActivity(i);
				break;
			}
		}
	}    
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	//public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.main, menu);

		btnLogin = menu.findItem(R.id.btn_login);
		btnLogout = menu.findItem(R.id.btn_logout);
		btnSearch = menu.findItem(R.id.btn_search);
		btnProfile = menu.findItem(R.id.btn_profile);

		
		if( ZingMeSDK.getInstance().isSessionValid(MainActivity.this)) {
			btnLogin.setVisible(false);
			btnLogout.setVisible(true);
        }
		
		return true;
	}
	
	 @Override
	  public boolean onOptionsItemSelected(MenuItem item) {
		 switch (item.getItemId()) {
		    case R.id.btn_login:
		    {
		    	if(ZingMeSDK.getInstance().isSessionValid(MainActivity.this)) {    	        	
    				btnLogin.setVisible(false);
    				btnLogout.setVisible(true);
    	        }
        		 else {
        			requestZingMeLogin();     
        			/*String fields = "id,username,displayname,tinyurl";
             		ZingMeSDK.getInstance().getMeInfo(MainActivity.this.getApplicationContext(), fields, new MeInfoRequestListener());
             		new ConfirmUserInfo().execute();*/
        		 }
		    	flatLogin = true;
		    	break;
		    }
		    case R.id.btn_logout:	
		    {
		    	AlertDialog.Builder alert = new AlertDialog.Builder(this);
		    	alert.setTitle("Chú ý");
		    	alert.setMessage("Bạn có muốn đăng xuất?");

	    	    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    	        public void onClick(DialogInterface dialog, int whichButton) {
	    	            //Your action here
	    	        	ZingMeSDK.getInstance().logout(getApplicationContext());
	    				
	    				if( !ZingMeSDK.getInstance().isSessionValid(MainActivity.this) ) {					
	    					btnLogin.setVisible(true);
	        				btnLogout.setVisible(false);
	    				}
	    				flatLogin = false;	
	    				
	    				Intent intent = new Intent(Intent.ACTION_MAIN);
	    				intent.addCategory(Intent.CATEGORY_HOME);
	    				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    				startActivity(intent);
	    	        }
	    	    });

	    	    alert.setNegativeButton("Cancel",
	    	        new DialogInterface.OnClickListener() {
	    	            public void onClick(DialogInterface dialog, int whichButton) {
	    	            }
	    	        });

	    	    alert.show();
	    	    break;		    	
		    }
		    case R.id.btn_profile:
		    {
		    	Intent i=new Intent(MainActivity.this,ProfileUserActivity.class);
		        i.putExtra("userid", Integer.toString(uid));
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", displayname);
		        i.putExtra("useravatarurl", tinyurl);
		        
		        i.putExtra("useridView","");
		        i.putExtra("usernameView", "");
		        i.putExtra("userdisplaynameView","");
		        i.putExtra("useravatarurlView", "");
			    startActivity(i);
		    	break;
		    }
		    	
		    case R.id.btn_search:
		    {
		    	Intent i=new Intent(getApplicationContext(),ListPlaceActivity.class);
		    	i.putExtra("userid",Integer.toString(uid));
		        i.putExtra("username", username);
		        i.putExtra("userdisplayname", displayname);
		        i.putExtra("useravatarurl", tinyurl);
			    startActivity(i);
			    break;
		    }
		 }
		 return super.onOptionsItemSelected(item);
	  }
	
	public void requestZingMeLogin() {
		try{
	    	String state = Double.toString(java.lang.Math.random());
	    	ZingMeSDK.getInstance().authorize(this, state, new ZME_DialogListener() {
	    		public void onComplete(Bundle values ) {
	    			if(ZingMeSDK.getInstance().isSessionValid(MainActivity.this)) {
	    				Log.d(TAG, ZingMeSDK.getInstance().getZME_Base().getAuthorizationCode());
	        			Log.d(TAG, ZingMeSDK.getInstance().getZME_Base().getAccessToken());
	        			editor = mPrefs.edit();
	        			editor.putString("access_token", ZingMeSDK.getInstance().getZME_Base().getAccessToken());
	        			editor.putLong("access_expires", ZingMeSDK.getInstance().getZME_Base().getAccessExpires());
	        			
	        			long now = System.currentTimeMillis();
	        			long expire = ZingMeSDK.getInstance().getZME_Base().getAccessExpires();
	        			
	        			long diff = (expire - now) / 1000;
	        			
	        			Log.d(TAG, "at will expire in " + diff + " secs");
	        			
	        			editor.commit();
	        			
	        			MainActivity.this.runOnUiThread(new Runnable() {
	        				public void run() {
	        					if(btnLogin != null && btnLogout != null){
	        						btnLogin.setVisible(false);
	        						btnLogout.setVisible(true);
	        						String fields = "id,username,displayname,tinyurl";
	        	             		ZingMeSDK.getInstance().getMeInfo(MainActivity.this.getApplicationContext(), fields, new MeInfoRequestListener());
	        	             		new ConfirmUserInfo().execute();
	        					}
	
	        					//btnNearHere.setVisibility(View.INVISIBLE);
	            			}
	        			});         			
	        			
	    			}
	    			else {
	    				ZingMeSDK.getInstance().logout(getApplicationContext());
	    			}
	    		}
	    		
	    		public void onZmeError(ZME_Error e){
	    			btnLogin.setVisible(false);
					btnLogout.setVisible(true);
	    			Log.d(TAG,"got error with ZME with error_code=" + e.getErrorCode());
	    			if(e.getErrorCode() == ZME_Error.ZOAUTH_ERR_USER_HAD_LOGGED_OUT || e.getErrorCode() == ZME_Error.ZOAUTH_ERR_AUTHORIZED_CODE_EXPIRED || e.getErrorCode() == ZME_Error.ZOAUTH_ERR_WRONG_VALIDATE_APLLICATION) {
	    				ZingMeSDK.getInstance().logout(getApplicationContext());
	    				//loginBtn.setVisibility(View.VISIBLE); ==> show login button or re-sho login form
	    				MainActivity.this.runOnUiThread(new Runnable() {
	    	                public void run() {
	    	                	requestZingMeLogin(); //re-show login form
	    	                }
	    	            });  
	    			}
	    		};
	    		
	    	    public void onError(ZME_DialogError e){
	    	    	Log.d(TAG, "got error with system");
	    	    }
	
				public void onCancel() {
					// TODO Auto-generated method stub
					
				};
	    	    
	    	});
	    }  catch (Exception e) {            
           e.printStackTrace();
            
           runOnUiThread(new Runnable() {
               public void run() {
                   //messageText.setText("Got Exception : see logcat ");
                   Toast.makeText(MainActivity.this, "Got Exception : see logcat ", 
                           Toast.LENGTH_SHORT).show();
               }
           });
           Log.e("Login to server Exception", "Exception : "
                                            + e.getMessage(), e);  
       }
	}

	public class MeInfoRequestListener extends BaseRequestListener {
    	public void onComplete( Object data ) {
//    		
    		try {
    			
    			if(data != null && data.getClass() == JSONObject.class) {
    				JSONObject info = (JSONObject) data;     			
        			
        			uid = info.optInt("id", 0);
        			username = info.optString("username", "");
        			displayname = info.optString("displayname", "");
        			tinyurl = info.optString("tinyurl", "");
        			final String out =  "uid=" + uid + "-username=" + username + "-displayname=" + displayname + "-tinyurl=" + tinyurl;        			
        		      
            		MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                        	/*edtSearch.setVisibility(View.VISIBLE);
                        	edtSearch.setText(out);
                        	Toast.makeText(MainActivity.this, out,
                                    Toast.LENGTH_LONG).show();*/
                        	
                        }
                    });
    			}
    			
    			
    		}
    		catch(Exception ex) {
    			Log.e(TAG, "Exception in MeInfoRequestListener.onComplete", ex);
    		}
    		
    		
    	}
    	
    	public void onZmeError(final ZME_Error e){
    		if(e.getErrorCode() == ZME_Error.ZOAUTH_ERR_ACCESSTOKEN_EXPIRED) {
    			ZingMeSDK.getInstance().logout(getApplicationContext());
    		}    		
    	}    	
    }
	
	//Insert new DetailGroupCustomerPlace
    class ConfirmUserInfo extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /*pDialog = new ProgressDialog(NewPostActivity.this);
            pDialog.setMessage("Creating DetailUtilityPlace...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();*/
        }
 
        /**
         * Creating place
         * */
        protected String doInBackground(String... args) {
            //String place_name = edtxtPlaceName.getText().toString();
            //String address = edtxtAddress.getText().toString();
        	
        	UserInfoData pc = new UserInfoData(Integer.toString(uid), username, displayname, tinyurl);   
			pc.ConfirmDataUser();
            return null;
        }
   
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            //pDialog.dismiss();
        } 
    }

}

